package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.HexCodec;
import top.codedance.iotp.common.util.JsonUtil;
import top.codedance.iotp.common.util.SystemUtil;
import top.codedance.iotp.iot.sdk.PublicStandandService;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.bean.SpliteStatus;

import javax.swing.*;
import javax.xml.bind.DatatypeConverter;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author xuedianfu
 */
public class HttpApiTester extends javax.swing.JDialog {
    private ShellFrame sf;
    private WaitLoading waitLoading = new WaitLoading(this);
    private JSONObject currentConnectionParam;
    private DefaultComboBoxModel<String> dlmB;
    public JSONObject connectData = new JSONObject();
    private Map<String, String> apiUrls = new HashMap<>();
    private SpliteStatus ss = new SpliteStatus(false, 0.3, 0);
    private Map<String, String> reqeustTemplates = new HashMap<>();
    private HexCodec hc = new HexCodec();

    /**
     * Creates new form HttpApiTester
     */
    public HttpApiTester(ShellFrame sf) {
        super(sf, true);
        this.sf = sf;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                if (!ss.isMin()) {
                    ss.setPercentage(0.3);
                } else {
                    ss.setWidth(jsp_body.getParent().getWidth());
                }
                resetComponent();
            }
        });
        setLocationRelativeTo(this.sf);
        setMinimumSize(new Dimension(1200, 800));
        setTitle("代码飞舞采控系统-HTTP接口测试器");

        initList();
        initRequestTemplates();
        initApiUrls();
        initApiList();
    }

    private void resetComponent() {
        if (ss.isMin()) {
            jsp_body.setDividerLocation(ss.getWidth());
        } else {
            jsp_body.setDividerLocation(ss.getPercentage());
        }
    }

    public void initList() {
        dlmB = new DefaultComboBoxModel<>();
        this.jcb_connects.setModel(dlmB);
        initListData();
    }

    public void initListData() {
        String s = SystemUtil.readTempFile(ConnectionManager.CONNECTION_TMP_FILENAME);
        if (null != s && !s.isEmpty()) {
            connectData = JSON.parseObject(s);
            dlmB.removeAllElements();
            Set<Map.Entry<String, Object>> entries = connectData.entrySet();
            JSONObject jo;
            for (Map.Entry<String, Object> entry : entries) {
                jo = (JSONObject) entry.getValue();
                if (jo.containsKey("type") && jo.getString("type").equals("http")) {
                    dlmB.addElement(entry.getKey());
                }
            }
            this.jcb_connects.repaint();
            getConnect();
        }
    }

    private JSONObject getConnect() {
        String key = (String) jcb_connects.getSelectedItem();
        currentConnectionParam = this.connectData.getJSONObject(key);
        return currentConnectionParam;
    }

    private void initRequestTemplates() {
        reqeustTemplates.put("genericdb", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"sql\": \"select * from oil_send\"\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("mysql", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"sql\": \"select * from oil_send\"\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("mssql", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"sql\": \"select * from mytable1\"\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("oracle", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"sql\": \"select * from \\\"book\\\" b\"\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("system_command", "{\n" +
                "      \"command\": \"netstat -ano\" 或 \"command\": {\"cmd\": \"GET-PROCESS\", \"powershell\": true}\n" +
                "}");
        reqeustTemplates.put("com", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"command\": \"0169323031303003\",\n" +
                "          \"hex\": false\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("udp", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"command\": \"0169323031303003\"\n" +
                "          \"hex\": false\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("http", "{\n" +
                "      \"command\": {\n" +
                "          \"method\": \"get\",\n" +
                "          \"protocol\": \"http\",\n" +
                "          \"url\": \"//vpn.devops.bamtechnology.cn/vpnclients3.php?username=codedance&password=codedance2022\"\n" +
                "          \"headers\": {\n" +
                "               \"Content-Type\": \"application/json;charset=utf-8\"\n" +
                "           }\n" +
                "          \"requestBody\": \"{}\"\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("pushData", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("opc", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"tags\": [ \"通道 1.设备 1.标记 1\" ]\n" +
                "          或\n" +
                "          \"tags\": [{\"ns\": 2, \"tag\": \"xuedianfu.2022.arg\", \"isWrite\": true, \"value\": 45}, {\"ns\": 2, \"tag\": \"xuedianfu.2022.name\"}, {\"ns\": 2, \"tag\": \"xuedianfu.2022.persion\"}]\n" +
                "          或\n" +
                "          \"tags\": [{\"tag\": \"xuedianfu.2022.arg\", \"isWrite\": true, \"value\": 45}, {\"tag\": \"xuedianfu.2022.name\"}]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("can", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"canId\": 1, \"cmd\": \"AB3DF\"},\n" +
                "              {\"tag\": \"tag1\", \"canId\": 2, \"cmd\": \"AB3DE\"},\n" +
                "              {\"tag\": \"tag2\", \"canId\": 3, \"cmd\": \"AB3D3\"}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("dnp", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("bacnet", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"tag0\", \"deviceId\": 1, \"property\": 85, \"datatype\": 0, \"instance\": 0, \"isWrite\": true, \"value\": 1244},\n" +
                "              {\"tag\": \"tag1\", \"deviceId\": 1, \"property\": 85, \"datatype\": 0, \"instance\": 0}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("iec", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("mtconnect", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("profibus", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("profinet", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("modbus", "{\n" +
                "      \"client\": {\n" +
                "          \"id\": 0,\n" +
                "          \"items\": [\n" +
                "              {\"tag\": \"abc\", \"function\": 3, \"slaveId\": 1, \"offset\": 0, \"datatype\": 3, \"isWrite\": true, \"value\": 12212},\n" +
                "              {\"tag\": \"tag2\", \"function\": 3, \"slaveId\": 1, \"offset\": 2, \"datatype\": 3}\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("client_plugins_params_get", "{}");
        reqeustTemplates.put("client_plugins_params_set", "{\n" +
                "      \"params\": {\n" +
                "          \"mysql\": {\n" +
                "                \"jdbcUrl\": \"jdbc:mysql://10.229.40.252:3306/epsdb?characterEncoding=UTF-8&serverTimezone=GMT%2B8\",\n" +
                "                \"user\": \"root_s\",\n" +
                "                \"password\": \"root@s\"\n" +
                "            },\n" +
                "            \"mssql\": {\n" +
                "                \"jdbcUrl\": \"jdbc:sqlserver://10.229.40.252:3306;databaseName=epsdb\",\n" +
                "                \"user\": \"root_s\",\n" +
                "                \"password\": \"root@s\"\n" +
                "            },\n" +
                "            \"oracle\": {\n" +
                "                \"jdbcUrl\": \"jdbc:oracle:thin:@localhost:1521:SID\",\n" +
                "                \"user\": \"root_s\",\n" +
                "                \"password\": \"root@s\"\n" +
                "            },\n" +
                "            \"opc\": {\n" +
                "                \"type\": \"da\",\n" +
                "                \"endpointUrl\": \"opc.tcp://192.168.0.45:49380\",\n" +
                "                \"host\": \"192.168.0.114\",\n" +
                "                \"domain\": \"\",\n" +
                "                \"progId\": \"SWToolbox.TOPServer.V5\",\n" +
                "                \"user\": \"codedance\",\n" +
                "                \"password\": \"123456\"\n" +
                "            },\n" +
                "            \"opw\": {\n" +
                "                \"newBaudRate\": \"9600\",\n" +
                "                \"newDataBits\": \"8\",\n" +
                "                \"newStopBits\": \"1\",\n" +
                "                \"newParity\": \"0\"\n" +
                "            },\n" +
                "            \"modbus\": {\n" +
                "                \"host\": \"192.168.0.45\",\n" +
                "                \"port\": \"502\"\n" +
                "            },\n" +
                "            \"live\": {\n" +
                "                \"ffmpegPath\": \"D:/working/ffmpeg/bin/ffmpeg.exe\"\n" +
                "            }\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("client_boot_params_get", "{}");
        reqeustTemplates.put("client_boot_params_set", "{\n" +
                "      \"params\": \"参数内容\"\n" +
                "}");
        reqeustTemplates.put("client_shutdown", "{\n" +
                "      \"client\": {\n" +
                "            \"isExceptionExit\": true,\n" +
                "            \"amount\": 10\n" +
                "    }\n" +
                "}");
        reqeustTemplates.put("client_view_version", "{}");
        reqeustTemplates.put("client_view_infomation", "{}");
        reqeustTemplates.put("server_client_version_set", "{\n" +
                "    \"versionCode\": 3\n" +
                "}");
        reqeustTemplates.put("server_information", "{}");
        reqeustTemplates.put("server_device_list", "{}");
        reqeustTemplates.put("server_user_list", "{}");
        reqeustTemplates.put("server_user_delete", "{\n" +
                "      \"id\": \"6\"\n" +
                "}");
        reqeustTemplates.put("server_device_delete", "{\n" +
                "      \"id\": \"4\"\n" +
                "}");
        reqeustTemplates.put("server_device_add", "{\n" +
                "      \"devices\": [\n" +
                "          {\n" +
                "              \"deviceId\": \"1234567890\",\n" +
                "              \"unitName\": \"测试10\"\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        reqeustTemplates.put("server_user_add", "{\n" +
                "      \"users\": [\n" +
                "          {\n" +
                "              \"deviceId\": \"1234567890\",\n" +
                "              \"username\": \"liulei456\",\n" +
                "              \"isAdmin\": 0,\n" +
                "              \"password\": \"123456\"\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        reqeustTemplates.put("server_registed_deviceIds", "{}");
    }

    private void initApiUrls() {
        apiUrls.put("genericdb", "/client/generic/db/query");
        apiUrls.put("mysql", "/client/mysql/query");
        apiUrls.put("mssql", "/client/mssql/query");
        apiUrls.put("oracle", "/client/oracle/query");
        apiUrls.put("system_command", "/client/system/command");
        apiUrls.put("com", "/client/com/command");
        apiUrls.put("udp", "/client/udp/command");
        apiUrls.put("http", "/client/http/command");
        apiUrls.put("pushData", "/client/pushData/get");
        apiUrls.put("opc", "/client/opc/command");
        apiUrls.put("can", "/client/can/command");
        apiUrls.put("dnp", "/client/dnp/command");
        apiUrls.put("bacnet", "/client/bacnet/command");
        apiUrls.put("iec", "/client/iec/command");
        apiUrls.put("mtconnect", "/client/mtconnect/command");
        apiUrls.put("profibus", "/client/profibus/command");
        apiUrls.put("profinet", "/client/profinet/command");
        apiUrls.put("modbus", "/client/modbus/command");
        apiUrls.put("client_plugins_params_get", "/client/plugins/params/get");
        apiUrls.put("client_plugins_params_set", "/client/plugins/params/set");
        apiUrls.put("client_boot_params_get", "/client/boot/params/get");
        apiUrls.put("client_boot_params_set", "/client/boot/params/set");
        apiUrls.put("client_shutdown", "/client/shutdown");
        apiUrls.put("client_view_version", "/client/view/version");
        apiUrls.put("client_view_infomation", "/client/view/infomation");
        apiUrls.put("server_client_version_set", "/server/client/version/set");
        apiUrls.put("server_information", "/server/information");
        apiUrls.put("server_device_list", "/server/device/list");
        apiUrls.put("server_user_list", "/server/user/list");
        apiUrls.put("server_user_delete", "/server/user/delete");
        apiUrls.put("server_device_delete", "/server/device/delete");
        apiUrls.put("server_device_add", "/server/device/add");
        apiUrls.put("server_user_add", "/server/user/add");
        apiUrls.put("server_registed_deviceIds", "/server/registed/deviceIds");
    }

    private void initApiList() {
        DefaultComboBoxModel<String> apiList = new DefaultComboBoxModel<>();
        apiList.addElement("genericdb");
        apiList.addElement("mysql");
        apiList.addElement("mssql");
        apiList.addElement("oracle");
        apiList.addElement("system_command");
        apiList.addElement("com");
        apiList.addElement("udp");
        apiList.addElement("http");
        apiList.addElement("pushData");
        apiList.addElement("opc");
        apiList.addElement("can");
        apiList.addElement("dnp");
        apiList.addElement("bacnet");
        apiList.addElement("iec");
        apiList.addElement("mtconnect");
        apiList.addElement("profibus");
        apiList.addElement("profinet");
        apiList.addElement("modbus");
        apiList.addElement("client_plugins_params_get");
        apiList.addElement("client_plugins_params_set");
        apiList.addElement("client_boot_params_get");
        apiList.addElement("client_boot_params_set");
        apiList.addElement("client_shutdown");
        apiList.addElement("client_view_version");
        apiList.addElement("client_view_infomation");
        apiList.addElement("server_client_version_set");
        apiList.addElement("server_information");
        apiList.addElement("server_device_list");
        apiList.addElement("server_user_list");
        apiList.addElement("server_user_delete");
        apiList.addElement("server_device_delete");
        apiList.addElement("server_device_add");
        apiList.addElement("server_user_add");
        apiList.addElement("server_registed_deviceIds");
        this.jcb_api.setModel(apiList);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jcb_connects = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        jcb_api = new javax.swing.JComboBox<>();
        jb_submit = new javax.swing.JButton();
        jb_clear = new javax.swing.JButton();
        jb_help = new javax.swing.JButton();
        jsp_body = new javax.swing.JSplitPane();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jta_response = new javax.swing.JTextArea();
        jb_responseFormat = new javax.swing.JButton();
        jcb_autoFormat = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jta_request = new javax.swing.JTextArea();
        jb_requestFormat = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("连接：");

        jLabel2.setText("接口：");

        jb_submit.setBackground(new java.awt.Color(255, 51, 0));
        jb_submit.setForeground(new java.awt.Color(255, 255, 255));
        jb_submit.setText("提交");
        jb_submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_submitActionPerformed(evt);
            }
        });

        jb_clear.setText("清空内容");
        jb_clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_clearActionPerformed(evt);
            }
        });

        jb_help.setText("请求参数模板");
        jb_help.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_helpActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_connects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcb_api, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jb_submit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jb_help)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jb_clear)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcb_connects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jcb_api, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_submit)
                    .addComponent(jb_clear)
                    .addComponent(jb_help))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jsp_body.setDividerLocation(50);
        jsp_body.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel4.setText("响应体：");

        jta_response.setEditable(false);
        jta_response.setColumns(20);
        jta_response.setRows(5);
        jScrollPane2.setViewportView(jta_response);

        jb_responseFormat.setText("JSON格式化");
        jb_responseFormat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_responseFormatActionPerformed(evt);
            }
        });

        jcb_autoFormat.setText("自动格式化");
        jcb_autoFormat.setToolTipText("");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 947, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jcb_autoFormat)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jb_responseFormat)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jb_responseFormat)
                    .addComponent(jcb_autoFormat))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
                .addContainerGap())
        );

        jsp_body.setRightComponent(jPanel3);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("请求体:");

        jta_request.setColumns(20);
        jta_request.setRows(5);
        jScrollPane1.setViewportView(jta_request);

        jb_requestFormat.setText("JSON格式化");
        jb_requestFormat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_requestFormatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 947, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jb_requestFormat)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jb_requestFormat))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 16, Short.MAX_VALUE)
                .addContainerGap())
        );

        jsp_body.setLeftComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jsp_body)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jsp_body)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jb_submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_submitActionPerformed
        String data = jta_request.getText();
        if(!data.trim().equals("")) {
            JSONObject connect = getConnect();
            if(connect != null) {
                JSONObject jo = JSON.parseObject(data);
                jo.put("deviceId", connect.getString("deviceId"));
                jo.put("username", connect.getString("username"));
                jo.put("password", connect.getString("password"));
                waitLoading.open();
                TerminalApplication.pool.submit(() -> {
                    try {
                        String action = jcb_api.getSelectedItem().toString();
                        if(action.equals("com") || action.equals("udp")){
                            JSONObject client = jo.getJSONObject("client");
                            if(client.containsKey("hex") && client.getBoolean("hex")){
                                client.put("command", DatatypeConverter.printHexBinary(hc.toBytes(client.getString("command"))));
                            }
                        }
                        PublicStandandService ss = new PublicStandandService(connect.getString("url"));
                        JSONObject response = ss.request(apiUrls.get(jcb_api.getSelectedItem().toString()), jo.toJSONString());
                        jta_response.setText(jcb_autoFormat.isSelected() ? JsonUtil.getInstance().format(response.toJSONString()) : response.toJSONString());
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(rootPane, "请求体必须是一个可转化为JSON对象的字符串。");
                    } finally {
                        waitLoading.close();
                    }
                });
            }else{
                JOptionPane.showMessageDialog(rootPane, "连接不能为空。");
            }
        }else{
            JOptionPane.showMessageDialog(rootPane, "请求数据不能为空。");
        }
    }//GEN-LAST:event_jb_submitActionPerformed

    private void jb_clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_clearActionPerformed
        jta_request.setText("");
        jta_response.setText("");
    }//GEN-LAST:event_jb_clearActionPerformed

    private void jb_requestFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_requestFormatActionPerformed
        jta_request.setText(JsonUtil.getInstance().format(jta_request.getText()));
    }//GEN-LAST:event_jb_requestFormatActionPerformed

    private void jb_responseFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_responseFormatActionPerformed
        jta_response.setText(JsonUtil.getInstance().format(jta_response.getText()));
    }//GEN-LAST:event_jb_responseFormatActionPerformed

    private void jb_helpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_helpActionPerformed
        jta_request.setText(reqeustTemplates.get(jcb_api.getSelectedItem()));
    }//GEN-LAST:event_jb_helpActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jb_clear;
    private javax.swing.JButton jb_help;
    private javax.swing.JButton jb_requestFormat;
    private javax.swing.JButton jb_responseFormat;
    private javax.swing.JButton jb_submit;
    private javax.swing.JComboBox<String> jcb_api;
    private javax.swing.JCheckBox jcb_autoFormat;
    private javax.swing.JComboBox<String> jcb_connects;
    private javax.swing.JSplitPane jsp_body;
    private javax.swing.JTextArea jta_request;
    private javax.swing.JTextArea jta_response;
    // End of variables declaration//GEN-END:variables
}
